package org.anno.chunkdb.backend;

import com.google.common.primitives.UnsignedBytes;

import java.nio.charset.StandardCharsets;

/**
 * A substring of a byte array, representing UTF-8 encoded strings.
 */
public class ByteSlice implements Comparable<ByteSlice> {

  private final byte[] data;
  private final int start;
  private final int end;

  public ByteSlice(byte[] data, int start, int end) {
    this.data = data;
    this.start = start;
    this.end = end;
  }

  public String toString() {
    return new String(data, start, end-start, StandardCharsets.UTF_8);
  }

  @Override
  public int compareTo(ByteSlice other) {
    int length = end - start;
    int otherLength = other.end - other.start;
    int minLength = Math.min(length, otherLength);
    for (int i = 0; i < minLength; i++) {
      int result = UnsignedBytes.compare(data[start + i], other.data[other.start + i]);
      if (result != 0) {
        return result;
      }
    }
    return length - otherLength;
  }
}
